package com.gack.business.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import io.jsonwebtoken.lang.Collections;

/**
 * 
 * @author ws
 * 2018-8-21
 */
@Repository
public class MessageDao {

	@Autowired
	private EntityManager em;
	
	/**
	 * 将状态为oldStatus的message状态置为newStatus
	 * @param oldStatus 旧状态
	 * @param newStatus 新状态
	 * @param detailIdList 详细信息id
	 * @return
	 */
	public int updateStatusByDetailIds(int oldStatus, int newStatus, List<String> detailIdList){
		if(Collections.isEmpty(detailIdList)){
			return 0;
		}
		
		String jpql = "update Message"
				+ " set state=:newStatus"
				+ " where state=:oldStatus"
				+ " and detailId in ";
		
		StringBuilder sb = new StringBuilder("(");
		for(String element : detailIdList){
			sb.append("'" + element + "', ");
		}
		sb = new StringBuilder(sb.substring(0, sb.length() - ", ".length()));
		sb.append(")");
		jpql += sb.toString();
		
		Query query = em.createQuery(jpql);
		query.setParameter("oldStatus", oldStatus);
		query.setParameter("newStatus", newStatus);
		
		return query.executeUpdate();
	}
	
}
